package com.ly.dingTalk.util.json;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import cn.hutool.core.collection.CollUtil;

public class DeptIdsToStrAdapter implements JsonSerializer<List<Long>>, JsonDeserializer<List<Long>> {

    @Override
    public List<Long> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonArray asJsonArray = json.getAsJsonArray();
        ArrayList<Long> newArrayList = null;
        if (asJsonArray != null && !asJsonArray.isEmpty()) {
            newArrayList = CollUtil.newArrayList();
            for (JsonElement jsonElement : asJsonArray) {
                Long asLong = jsonElement.getAsJsonPrimitive().getAsLong();
                newArrayList.add(asLong);
            }
        }
        return newArrayList;
    }

    @Override
    public JsonElement serialize(List<Long> src, Type typeOfSrc, JsonSerializationContext context) {
        JsonElement result = null;
        if (CollUtil.isNotEmpty(src)) {
            result = new JsonPrimitive(CollUtil.join(src, ","));
        }
        return result;
    }

}
